package main.java.com.lee.pattern.asynccallback.jdk;

import java.util.concurrent.*;
import java.util.function.Function;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/2/21
 */
public class CompletableFutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        String text = "message";
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 创建CompletionStage.
        // runnable 任务, 无输入, 无输出, 默认线程池
        CompletableFuture<Void> runFutureWithForkJoinPool = CompletableFuture.runAsync(() -> System.out.println(text));
        // runnable 任务, 无输入, 无输出, 自定义线程池
        CompletableFuture<Void> runFutureWithThreadPool = CompletableFuture.runAsync(() -> System.out.println("I am runnable with executors"));

        // supplier 任务, 无输入, 有输出, 默认线程池
        CompletableFuture<String> supplierFutureWithForkJoinPool = CompletableFuture.supplyAsync(() -> {
            System.out.println("I am supplier with fork join pool");
            return "supplier with forkjoin pool";
        });
        // supplier 任务, 无输入, 有输出, 自定义线程池
        CompletableFuture<String> supplierFutureWithExecutors = CompletableFuture.supplyAsync(() -> {
            System.out.println("I am supplier with fork join pool");
            return "supplier with forkjoin pool";
        }, executorService);


        // 任务完成回调, Async是异步回调, 可指定线程池
        runFutureWithForkJoinPool.whenComplete((t, u) -> {
            System.out.println("执行完成");
        });
        // 为任务设置异常回调钩子.
        CompletableFuture<Void> future = runFutureWithForkJoinPool.exceptionally((e -> {
            System.out.println(e.getMessage());
            return null;
        }));


        // 返回值和异常统一处理
        future.handle((t, u)->{
            if (u == null) {
                System.out.println("no exception");
            } else {
                System.out.println("exception");
            }
            return null;
        });

        future.get();
    }


}
